package com.itheima.filter;

import com.itheima.bean.Employee;
import com.itheima.bean.User;
import com.itheima.utils.BaseContext;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter("/front/*")
public class loginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        HttpServletRequest req = (HttpServletRequest) servletRequest;

        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        String uri = req.getRequestURI();
        //if (!uri.contains("front")) {
        //    filterChain.doFilter(req, resp);
        //    return;
        //}
        if (uri.contains("login") || uri.endsWith(".css") || uri.endsWith(".js")
                || uri.contains("images") || uri.contains("plugin") || uri.contains("style")
                || uri.endsWith(".ico") || uri.contains("sms")) {
            filterChain.doFilter(req, resp);
            return;
        }
        User user = (User) req.getSession().getAttribute("user");

        if (user != null) {

            //存储该用户的id到threadlocal
            BaseContext.setCurrentId(user.getId());

            filterChain.doFilter(servletRequest, servletResponse);

            return;
        }


        //5. 如果没有进入上面的if，即表示该请求，不属于直接放行的请求，也没有登录。要跳转登录页面

        resp.sendRedirect("/front/page/login.html");
    }
}
